<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/9/25 0025
  Time: 上午 11:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
    <jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>异常记录</cite>
        </a>
      </span>
</div>


<div class="x-body">
    <div class="layui-row">
        <form class="layui-form layui-col-md12" onsubmit="return false">

            <div class="layui-input-inline" style="width: 165px">
                <input class="layui-input" placeholder="请输入SAP/QAD" id="pam01" style="width: 150px">
            </div>
            <input type="hidden" id="dateTime">

            <div class="layui-input-inline" style="width: 150px">
                <input class="layui-input" id="date3" placeholder="输入开始时间"   style="width: 150px">
            </div>

            <div class="layui-input-inline" >
                -
            </div>

            <div class="layui-input-inline" style="width: 150px">
                <input class="layui-input" id="date4" placeholder="输入结束时间"  style="width: 150px">
            </div>

            <%--<input type="text" name="keyword2" id="keyword2" placeholder="请输入备注" autocomplete="off" class="layui-input">
            <input type="text" name="keyword3" id="keyword3" placeholder="请输入SAP/QAD" autocomplete="off" class="layui-input">
            <input type="text" name="keyword4" id="keyword4" placeholder="请输入中文名称" autocomplete="off" class="layui-input">--%>
            <button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
        </form>
    </div>
    <xblock>
        <button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
        <button class="layui-btn layui-btn-danger" id="del"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
        <%-- <button class="layui-btn layui-btn-danger" id="import"><i class="layui-icon layui-icon-download-circle"></i>导入</button>
         <button class="layui-btn layui-btn-danger" id="export"><i class="layui-icon layui-icon-upload"></i>导出</button>
         <button class="layui-btn layui-btn-danger" id="dybq"><i class="layui-icon layui-icon-upload-drag"></i>打印标签</button>--%>
    </xblock>
    <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
    <script type="text/html" id="rowToolbar">
        <a class="layui-btn layui-btn-xs" lay-event="update"><i class="layui-icon layui-icon-edit"></i>编辑</a>
        <a class="layui-btn layui-btn-xs" lay-event="updateByID"><i class="layui-icon layui-btn-loading"></i>完成</a>
    </script>
</div>

<div id="addDivID" style="display:none">
    <form class="layui-form" id="addFormID">
        <xblock>
            <table>
                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">供应商</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select  name="parameter1" lay-filter="materNum">
                                <c:forEach items="${allCustomerList }" var="customer">
                                <option value="${customer.id}">${customer.customer_name }</option>
                                </c:forEach>
                        </div>
                    </td>

                    <td><label class="layui-form-label">物料号</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select name="mid" id="deptIdSearch" lay-verify="deptIdSearch" lay-search></select>
                        </div>
                    </td>
                </tr>

                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">单据号</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select name="shippingDocuments" id="deptIdSearchs" lay-verify="deptIdSearchs" lay-search>
                                <c:forEach items="${shippingDocumentsList}" var="shippingDocuments">
                                    <option>${shippingDocuments}</option>
                                </c:forEach>
                            </select>
                        </div>
                    </td>
                    <td><label class="layui-form-label">到货日期</label></td>
                    <td>
                        <input class="layui-input" id="date2"  lay-verify="dueDate" name="anomRemarks2" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>
                </tr>

                <tr style="height: 10px"></tr>
                <tr>

                    <td><label class="layui-form-label">到货数量</label></td>
                    <td>
                        <input class="layui-input" id="maintenance" name="receiveNum" lay-verify="parameter2" type="number" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>

                    <td><label class="layui-form-label">收货数量</label></td>
                    <td>
                        <input class="layui-input"  name="codeNum" lay-verify="parameter2" type="number" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>

                </tr>
                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">异常描述</label></td>
                    <td colspan="3">
                       <textarea name="anomType" class="layui-textarea" placeholder="请输入异常描述" style="width:510px;height:25px"></textarea>
                    </td>
                </tr>
                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label></td>
                    <td colspan="3">
                        <textarea name="anomRemarks" class="layui-textarea" placeholder="请输入备注" style="width:510px;height:25px"></textarea>
                    </td>
                </tr>
                <tr style="height: 20px"></tr>
                <tr align="center">
                    <td colspan="2"><button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:190px; margin-bottom: 10px">提交</button></td>
                    <td colspan="2"><button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button></td>
                </tr>
            </table>
        </xblock>
    </form>
</div>

<div id="updateDivID" style="display:none">
    <form class="layui-form" id="updateFormID">
        <xblock>
            <table>
                <tr style="height: 10px"></tr>
                <tr>


                    <input type="hidden" name="anomId" >

                    <td><label class="layui-form-label">供应商</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select  name="parameter1" lay-filter="materNum">
<%--                                <c:forEach items="${allCustomerList }" var="customer">--%>
<%--                                    <option value="${customer.id}">${customer.customer_name }</option>--%>
<%--                                </c:forEach>--%>
                        </div>
                    </td>

                    <td><label class="layui-form-label">物料号</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select name="mid" id="deptIdSearchd" lay-verify="deptIdSearch" lay-search></select>
                        </div>
                    </td>
                </tr>

                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">单据号</label></td>
                    <td>
                        <div class="layui-input-inline" style="width:190px; float: left;">
                            <select name="shippingDocuments" id="deptIdSearchsd" lay-verify="deptIdSearchs" lay-search>
<%-- <c:forEach items="${shippingDocumentsList}" var="shippingDocuments">--%>
<%--<option>${shippingDocuments}</option>--%>
<%-- </c:forEach>--%>
                            </select>
                        </div>
                    </td>
                    <td><label class="layui-form-label">到货日期</label></td>
                    <td>
                        <input class="layui-input" id="date1"  lay-verify="dueDate" name="anomRemarks2" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>
                </tr>

                <tr style="height: 10px"></tr>
                <tr>

                    <td><label class="layui-form-label">到货数量</label></td>
                    <td>
                        <input class="layui-input" id="maintenanced" name="receiveNum" lay-verify="parameter2" type="number" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>

                    <td><label class="layui-form-label">收货数量</label></td>
                    <td>
                        <input class="layui-input"  name="codeNum" lay-verify="parameter2" type="number" style="width: 190px; display:inline">
                        <div class="layui-inline" style="margin-top: 10px;">
                            <span style="color:red; font-size: 24px; margin-left: 4px">*</span>
                        </div>
                    </td>

                </tr>
                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">异常描述</label></td>
                    <td colspan="3">
                        <textarea name="anomType" class="layui-textarea" placeholder="请输入异常描述" style="width:510px;height:25px"></textarea>
                    </td>
                </tr>
                <tr style="height: 10px"></tr>
                <tr>
                    <td><label class="layui-form-label">备&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注</label></td>
                    <td colspan="3">
                        <textarea name="anomRemarks" class="layui-textarea" placeholder="请输入备注" style="width:510px;height:25px"></textarea>
                    </td>
                </tr>
                <tr style="height: 20px"></tr>
                <tr align="center">
                    <td colspan="2"><button class="layui-btn layui-btn-blue" id="subBtns" lay-submit lay-filter="updateForm" style="margin-left:190px; margin-bottom: 10px">提交</button></td>
                    <td colspan="2"><button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button></td>
                </tr>
            </table>
        </xblock>
    </form>
</div>



<script>
    $(document).ready(function () {
        $('#dateTime').val(getNowFormatDate());
    })


    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }

    var form;
    var table;
    layui.use(['table','layer','upload','form','laydate'], function(){
        table = layui.table;
        form = layui.form;
        var laydate = layui.laydate;
        form.on('select(materNum)', function (data) {
            getMaterListStrWhere1(data.value)
        });

        laydate.render({
            elem: '#date3',
            type:'datetime',
            value: new Date()
        });

        laydate.render({
            elem: '#date4',
            type:'datetime',
            value: new Date()
        });

        laydate.render({
            elem: '#date2',
            type:'datetime',
            value: new Date()
        });

        laydate.render({
            elem: '#date1',
            type:'datetime'
        });

        var $ = layui.jquery, active = {
            reload:function () {
                var dateTime = $('#dateTime').val()
                if (dateTime.length < 4) {
                    var time = new Date();
                    var day = ("0" + time.getDate()).slice(-2);
                    var month = ("0" + (time.getMonth() + 1)).slice(-2);
                    var today = time.getFullYear() + "-" + (month);
                    dateTime = today;
                }

                var obj = {};

                obj["params01"] = $("#date3").val()
                obj["params02"] = $("#date4").val()

                table.reload('contentTable',{
                    method:'get'
                    ,where:{
                        'searchValue':'%'+$("#pam01").val()+'%',
                        'params':obj
                    }
                    ,page: {
                        curr: 1//重新从第 1 页开始
                    }
                });
            }
        }

        table.render({
            elem: '#tableList'
            ,id :'contentTable'
            , url: '/anomalyRecords/getAnomalyRecordsList.do'
            ,where:{
                'stockId':$('#keyword1').val(),
                'date':$('#dateTime').val()
            }
            ,toolbar: '#toolbar'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'},
                {field:'uid',
                    title:'序号',
                    sort: true,
                    width: 60,
                    type:'numbers',
                    align:'center'}
                ,{field:'searchValue', title:'供应商'}
                ,{field:'shippingDocuments', title:'单据号'}
                ,{field:'remark', title:'物料号'}
                ,{field:'receiveNum', title:'到货数量'}
                ,{field:'codeNum', title:'收货数量'}
                ,{field:'receiveDate', title:'到货时间'}
                ,{field:'anomState', title:'处理状态',templet:function (row) {
                        var state = ""
                        if (row.anomState.trim() === 'WC') {
                            state =  '未处理';
                        } else if (row.anomState.trim() === 'YC')  {
                            state =  '已处理';
                        }
                        return state
                    }}
                ,{field:'anomType', title:'异常描述'}
                ,{field:'anomRemarks', title:'备注'}
                ,{field:'', title:'操作',toolbar: '#rowToolbar'}
            ]]
            , page: true
            ,request: {   //如果无需自定义请求参数，可不加该参数
                pageName: 'page' //页码的参数名称，默认：page
                ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            ,response: {   //如果无需自定义数据响应名称，可不加该参数
                countName: 'total' //规定数据总数的字段名称，默认：count
                ,dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            ,done : function(res, curr, count){
                $('th').css({
                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                })
            }
        });

        //监听行工具事件
        table.on('tool(tableList)', function(obj){
            var data = obj.data
            console.log(obj.event)
            var event = obj.event
            if (event == 'update'){

                layer.open({
                    type: 1 				//Page层类型
                    ,area: ['670px', '530px'] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 			//遮罩透明度
                    ,maxmin: true 			//允许全屏最小化
                    ,anim: 1 				//0-6的动画形式，-1不开启
                    ,content: $('#updateDivID')
                    ,success: function(){
                        $('[name="anomId"]').val(data.anomId)
                        //到达时间
                        $('[name="anomRemarks2"]').val(data.anomRemarks2)
                        // 到货数量
                        $('[name="receiveNum"]').val(data.receiveNum)
                        //收货数量
                        $('[name="codeNum"]').val(data.codeNum)
                        //异常描述
                        $('[name="anomRemarks"]').val(data.anomRemarks)
                        //备注
                        $('[name="anomType"]').val(data.anomType)

                        //单据号
                        getReceiveNumber(data.shippingDocuments)
                        //供应商
                        getAllCustomerList(data.searchValue)

                        //物料号
                        getMaterListStrWhere(data.remark,data.anomRemarks3)

                        // $("input[name='itemName']").val("");
                        // $("input[name='startDate']").val("");
                        // $("input[name='dueDate']").val("");
                        // $("input[name='parameter2']").val("");
                        form.render();
                    }

                });
            }

            //完成
            if (event == 'updateByID') {

                getDelete("确定更改吗？",'update')

            }
        })


        $('.layui-col-md12 .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('.select .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });


        $("#add").click(function(){
            layer.open({
                type: 1 				//Page层类型
                ,area: ['670px', '530px'] 	//宽  高
                ,title: '新增'
                ,shade: 0.6 			//遮罩透明度
                ,maxmin: true 			//允许全屏最小化
                ,anim: 1 				//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,success: function(){
                    getMaterListStrWhere1($('[name = "parameter1"]').val())
                    $("input[name='itemName']").val("");
                    $("input[name='startDate']").val("");
                    $("input[name='dueDate']").val("");
                    $("input[name='parameter2']").val("");
                    form.render();
                }

            });
        });

        //批量删除
        $("#del").click(function(){
            getDelete("确定删除吗？",'delete')
        });

        form.verify({
            mid:function (value, item) {
                if(value.trim() == ''){
                    return '领料号不能为空';
                }
            },
            startDate:function (value, item) {
                if(value.trim() == ''){
                    return '日期不能为空';
                }
            },
            dueDate:function (value, item) {
                if(value.trim() == ''){
                    return '日期不能为空';
                }
            },
            parameter2:function (value, item) {
                if(value.trim() == ''){
                    return '数量不能为空';
                }
            },

            anomType:function (value, item) {
                if(value.trim() == ''){
                    return '异常描述不能为空';
                }
            }
        })

        /**  data:{itemName:"12",startDate:'2019-09-20'},
         * 通用表单提交(AJAX方式),totalMoney:100,startDate:'2019-09-20',dueDate:'2019-09-20'
         */
        form.on('submit(addForm)', function () {

            console.log($('#addFormID').serialize())

            $("#subBtn").attr("disabled",true);
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath }/anomalyRecords/addAnomalyRecords.do',
                data:$('#addFormID').serialize(),
                cache:false,
            }).done(
                function(res) {
                    if (res.flag) {
                        toastr.success('新增成功！');
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                }
            ).fail(
                function() {
                    toastr.error('新增失败！');
                    setTimeout(function(){
                        location.reload();
                    },1000);
                }
            )
            return false;
        })

        form.on('submit(updateForm)', function () {


            $("#subBtns").attr("disabled",true);
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath }/anomalyRecords/updateAnomalyRecords.do',
                data:$('#updateFormID').serialize(),
                cache:false,
            }).done(
                function(res) {
                    if (res.flag) {
                        toastr.success('修改成功！');
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                }
            ).fail(
                function() {
                    toastr.error('修改失败！');
                    setTimeout(function(){
                        location.reload();
                    },1000);
                }
            )
            return false;
        })


    });

    toastrStyle()

    function getReceiveNumber(shippingDocuments) {
        $('[name="shippingDocuments"]').empty()
        //收货单号
        $.ajax({
            type:"POST",
            url:'/anomalyRecords/getReceiveNumber.do',
            success:function (result) {
                $.each(result,function (index,row) {
                    if (shippingDocuments == row) {
                        $('[name="shippingDocuments"]').append(
                            '<option selected>'+row+'</option>'
                        )
                    }else {
                        $('[name="shippingDocuments"]').append(
                            '<option>'+row+'</option>'
                        )
                    }

                })
                form.render('select');
            }
        })
    }

    function getAllCustomerList(searchValue) {
        $('[name="parameter1"]').empty()
        //收货单号
        $.ajax({
            type:"POST",
            url:'/anomalyRecords/getAllCustomerList.do',
            success:function (result) {
                $.each(result,function (index,row) {
                    if (searchValue == row.customer_name) {
                        $('[name="parameter1"]').append(
                            '<option selected>'+row.customer_name+'</option>'
                        )
                    }else {
                        $('[name="parameter1"]').append(
                            '<option value="'+row.id+'">'+row.customer_name+'</option>'
                        )
                    }

                })
                form.render('select');
            }
        })
    }

    //物料号
    function getMaterListStrWhere(remark,anomRemarks3) {
        $('[name="mid"]').empty();      //清空
        $.ajax({
            type:"POST",
            url:"/anomalyRecords/getMaterListStrWhere.do",
            data:{customerId:anomRemarks3},
            success:function (result) {
                $.each(result,function (index,row) {

                    $('[name="mid"]').append(
                        "<option  value="+row.id+">" + row.materiel_num+ "</option>");

                    if (remark == row.materiel_num) {
                        $('[name="mid"]').find("option[value = "+row.id+"]").attr("selected","selected")
                    }
                })
                //append后必须从新渲染,这个问题找了一天，全是坑
                form.render('select');
            }
        })
    }


    function getMaterListStrWhere1(data) {
        $('[name="mid"]').empty();      //清空
        $.ajax({
            type:"POST",
            url:"/anomalyRecords/getMaterListStrWhere.do",
            data:{customerId:data},
            success:function (result) {
                $.each(result,function (index,row) {
                    $('[name="mid"]').append(
                        "<option value="+row.id+">" + row.materiel_num+ "</option>");

                })
                //append后必须从新渲染,这个问题找了一天，全是坑
                form.render('select');
            }
        })
    }

    //批量删除及完成
    function getDelete(value,type) {
        var rowData = table.checkStatus('contentTable');
        var data = rowData.data;
        var idArr = new Array();
        if(data.length == 0){
            toastrStyle();
            toastr.warning("请至少选择一条记录！");
        } else {
            for(var i=0;i < data.length;i++){
                idArr[i] = data[i].anomId;
            }
            $.ajax({
                type:'post',
                url:'${pageContext.request.contextPath }/anomalyRecords/deleteAnomalyRecords.do',
                data:{"ids" : idArr,"type":type},
                success:function(data){
                    layer.confirm(value, function(){
                        if(data.flag){
                            toastr.success("更改成功！");
                            setTimeout(function(){
                                location.reload();
                            },1000);
                            setTimeout(function(){
                                window.location.reload();
                            },2000);
                        }else{
                            toastr.warning("更改失败！");
                            location.reload();
                        }
                    });
                }
            });
        }
    }

</script>
</body>

</html>
